/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.oai.repositoryManager.items;

import cz.mzk.oai.repositoryManager.EntityNotFoundException;
import cz.mzk.oai.repositoryManager.EntityPresentException;
import cz.mzk.oai.repositoryManager.oaiId.OaiIdManager;
import cz.mzk.oai.repositoryManager.oaiId.OaiIdentifierEntity;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 *
 * @author Martin
 */
public class OaiIdManagerStub implements OaiIdManager {
    //Set<OaiIdentifierEntity> oaiIdSet = new HashSet<OaiIdentifierEntity>();

    Map<Long, OaiIdentifierEntity> idEntityMap = new HashMap<Long, OaiIdentifierEntity>();
    private Long idCounter = Long.valueOf(0);

    public OaiIdentifierEntity createOaiId(String base, String sysno) throws EntityPresentException {
        OaiIdentifierEntity entity = getOaiId(base, sysno);
        if (entity != null) {
            throw new EntityPresentException(OaiIdentifierEntity.class.getCanonicalName(), "base: '" + base + "', sysno: '" + sysno + "'");
        } else {
            entity = new OaiIdentifierEntity();
            entity.setId(getNewId());
            entity.setBase(base);
            entity.setSysno(sysno);
            idEntityMap.put(entity.getId(), entity);
            return entity;
        }
    }

    public OaiIdentifierEntity findOaiId(String base, String sysno) throws EntityNotFoundException {
        OaiIdentifierEntity entity = getOaiId(base, sysno);
        if (entity == null) {
            throw new EntityNotFoundException(OaiIdentifierEntity.class.getName(), "base: '" + base + "', sysno: '" + sysno);
        }
        return entity;
    }

    private OaiIdentifierEntity getOaiId(String base, String sysno) {
        Set<Long> keySet = idEntityMap.keySet();
        for (Long key : keySet) {
            OaiIdentifierEntity entity = idEntityMap.get(key);
            if (base.equals(entity.getBase()) && sysno.equals(entity.getSysno())) {
                return entity;
            }
        }
        return null;
    }

    private Long getNewId() {
        idCounter = Long.valueOf(idCounter.longValue() + 1);
        return idCounter;
    }

    public void removeOaiId(String base, String sysno) throws EntityNotFoundException {
        OaiIdentifierEntity item = getOaiId(base, sysno);
        if (item == null) {
            throw new EntityNotFoundException(OaiIdentifierEntity.class.getName(), "base: '" + base + "', sysno: '" + sysno);
        } else {
            idEntityMap.remove(item.getId());
        }
    }

    public void removeOaiId(OaiIdentifierEntity oaiId) throws EntityNotFoundException {
        OaiIdentifierEntity entity = idEntityMap.get(oaiId.getId());
        if (entity == null){
            throw new EntityNotFoundException(OaiIdentifierEntity.class.getCanonicalName(), Long.toString(oaiId.getId()));
        }
    }
}
